from typing import List, Union

from appium.webdriver import WebElement
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.interaction import POINTER_TOUCH
from selenium.webdriver.common.actions.pointer_input import PointerInput


# 多指同时点击封装类
class MultiFingerTouchUtil:

    def __init__(self, driver):
        self.driver = driver

    def tap_elements(self,
                     elements: List[WebElement] = None,
                     coordinates: List[tuple] = None,
                     duration: float = 0.1) -> None:
        """

        :param elements: 需要点击的元素列表
        :param coordinates: 元素坐标格式：[(x1, y1), (x2, y2)]
        :param duration: 点击持续时间， 默认0.1
        :return:
        """
        # 参数校验
        if not elements and not coordinates:
            raise ValueError("未提供参数")

        # 获取坐标列表

        if elements:
            coords = []
            for element in elements:
                loc = element.location
                size = element.size
                x = loc['x'] + size['width'] / 2
                y = loc['y'] + size['height'] / 2
                coords.append((x, y))
        else:
            coords = coordinates

        # 构建W3C Actions
        actions = ActionBuilder(self.driver)
        for idx, (x, y) in enumerate(coords):
            # 为每个触点添加唯一的指针名称（如finger0， finger1）
            pointer_input = PointerInput(PointerInput.POINTER_TOUCH, name=f"finger{idx}")
            pointer_name = f"finger{idx}"
            actions.add_pointer_input(pointer_input)
            actions.pointer_action.move_to_location(x, y).pointer_down().pause(duration).pointer_up()
            # # 移动到元素坐标位置
            # actions.w3c_actions.pointer_action.move_to_location(x, y)
            # # 按下元素
            # actions.w3c_actions.pointer_action.pointer_down()
            # # 按住元素
            # actions.w3c_actions.pointer_action.pause(duration)
            # # 松开元素
            # actions.w3c_actions.pointer_action.release()
        # 执行操作
        actions.perform()
